package com.learn.core.controller.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.learn.common.annotation.Log;
import com.learn.common.annotation.UserLoginToken;
import com.learn.common.enums.BusinessType;
import com.learn.common.enums.OperatorType;
import com.learn.common.enums.ResultEnum;
import com.learn.common.utils.*;
import com.learn.common.utils.result.CommonResult;
import com.learn.core.domain.LItem;
import com.learn.core.domain.LRole;
import com.learn.core.dto.LitemDTO;
import com.learn.core.service.ILItemService;
import com.learn.core.service.ILRoleService;
import com.learn.framework.web.controller.WebController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Description
 *
 * @author zhaohongyu
 * @ClassName LItemController
 * @date 2021.03.16 13:55
 */
@Api("菜单权限")
@RestController
@RequestMapping("/manager/item")
public class LItemController extends WebController<LItem> {

    @Autowired
    ILItemService ilItemService;
    @Autowired
    ILRoleService ilRoleService;

    //权限菜单树
    @ApiOperation(value = "权限菜单树")
    @UserLoginToken
    @GetMapping("/tree")
    public CommonResult<Object> tree(@RequestParam(value = "roleId",required = false)String roleId){
        try {
            QueryWrapper<LItem> queryWrapper = new QueryWrapper<LItem>();
            List<LItem> lItems = new ArrayList<>();
            if(roleId!=null){
                QueryWrapper<LRole> query = new QueryWrapper<LRole>();
                query.eq("role_id",roleId);
                LRole lRole = ilRoleService.getOne(query);
                if(StringUtils.isNotBlank(lRole.getRoleItem()) && lRole.getRoleItem().contains(",")) {
                    List<String> newsTypes = Arrays.asList(lRole.getRoleItem().split(","));
                    if(newsTypes.size() > 0){
                        queryWrapper.in("menu_id", newsTypes);
                        lItems = ilItemService.queryLItemAll(queryWrapper);
                    }
                }
            }else{
                lItems = ilItemService.queryLItemAll(queryWrapper);
            }

            if(lItems.size()>0)
                return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,lItems);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }

    //列表
    @ApiOperation(value = "获取列表")
    @UserLoginToken
    @PostMapping("/list")
    public PageResult<LItem> list(@RequestBody LitemDTO litemDTO){
        try {
            if (litemDTO==null||litemDTO.getPage()==null||litemDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(litemDTO.getPage(),litemDTO.getRows());
            QueryWrapper<LItem> queryWrapper = new QueryWrapper<LItem>();
            if(litemDTO.getParentId()!=null)
                queryWrapper.eq("parent_id",litemDTO.getParentId());
            if(litemDTO.getMenuName()!=null)
                queryWrapper.like("menu_name",litemDTO.getMenuName());
            if(litemDTO.getState()!=null)
                queryWrapper.eq("state",litemDTO.getState());
            if(litemDTO.getSeq()!=null)
                queryWrapper.orderByAsc(litemDTO.getSeq());
            Page<LItem> lItems = (Page<LItem>) ilItemService.list(queryWrapper);
            if (CollectionUtils.isEmpty(lItems)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            // 返回
            return new PageResult(lItems.getTotal(), lItems, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }


    //新增
    @ApiOperation(value = "添加")
    @PostMapping("/add")
    @UserLoginToken
    @Log(title = "添加菜单权限", businessType = BusinessType.INSERT, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> add(@RequestBody LItem lItem){
        try {
            if(lItem!=null) {
                if (StringUtils.isEmpty(lItem.getMenuName())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_ITEM_NAME);
                }
                if (StringUtils.isEmpty(lItem.getState())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_ITEM_STATE);
                }
                if (StringUtils.isEmpty(lItem.getSeq())) {
                    lItem.setSeq(0);
                }
                if (StringUtils.isEmpty(lItem.getParentId())) {
                    lItem.setParentId(0);
                }
                lItem.setCreateTime(new Date());
                if (ilItemService.save(lItem)) {
                    return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
                }
            }
        }catch (Exception e){
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return  (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }


    //删除
    @ApiOperation(value = "删除")
    @PostMapping("/del")
    @UserLoginToken
    @Log(title = "删除菜单权限", businessType = BusinessType.DELETE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> del(@RequestBody LItem lItem){
        try {
            if(lItem!=null){
                if(lItem.getMenuId()!=null){
                    List<Integer> ids = new ArrayList<>();
                    ids.add(lItem.getMenuId());
                    if(nodeStr(ids)){
                        return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
                    }
                }
            }
        }catch (Exception e)
        {
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    private Boolean nodeStr (List<Integer> lists) throws Exception{
        List<Integer> ids = new ArrayList<>();
        QueryWrapper<LItem> queryWrapper = new QueryWrapper<LItem>();
        for (int i = 0; i <lists.size() ; i++) {
            int orgid = lists.get(i);

            queryWrapper.eq("parent_id",orgid);
            List<LItem> lItems = ilItemService.list(queryWrapper);
            for (int j = 0; j < lItems.size(); j++) {
                LItem lItem = lItems.get(j);
                ids.add(lItem.getMenuId());
            }
        }
        if(ids.size() > 0){
            this.nodeStr(ids);
        }

        ids.addAll(lists);
        queryWrapper = new QueryWrapper<LItem>();
        queryWrapper.in(true, "menu_id", ids);
        ilItemService.remove(queryWrapper);

        return Boolean.TRUE;
    }

    //更新
    @ApiOperation(value = "更新")
    @PostMapping("/edit")
    @UserLoginToken
    @Log(title = "更新菜单权限", businessType = BusinessType.UPDATE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> edit(@RequestBody LItem lItem) {
        if(lItem!=null){
            lItem.setUpdateTime(new Date());
            if(ilItemService.updateById(lItem)){
                return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
            }
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }
}
